package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理异常
    @ExceptionHandler
    public Result ex(Exception e) {//方法形参中指定能够处理的异常类型
        log.error("发生异常信息", e);//打印堆栈中的异常信息
        //捕获到异常之后，响应一个标准的Result
        return Result.error("对不起,操作失败,请联系管理员");
    }

    /**
     * 处理请求体参数校验失败异常 (用于 @RequestBody)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringJoiner stringJoiner = new StringJoiner(",");
        for (FieldError fieldError : fieldErrors) {
            //没通过校验属性名
            String field = fieldError.getField();
            //没通过的提示信息
            stringJoiner.add(fieldError.getDefaultMessage());  //以逗号分隔拼接
            log.info(field + "：" + fieldError.getDefaultMessage());
        }
        return Result.error(stringJoiner.toString());
    }

    /**
     * 处理路径变量(@PathVariable)和请求参数(@RequestParam)校验失败异常
     */
    @ExceptionHandler(HandlerMethodValidationException.class)
    public Result handleHandlerMethodValidationException(HandlerMethodValidationException e) {
        StringJoiner stringJoiner = new StringJoiner(",");

        // 直接获取所有错误信息
        e.getAllErrors().forEach(error -> {
            stringJoiner.add(error.getDefaultMessage());
            log.info("参数校验失败：" + error.getDefaultMessage());
        });
        return Result.error(stringJoiner.toString());
    }

}